package com.lwx.service;

import com.lwx.domain.User;
import com.lwx.domain.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author draem
 * @create 2018-06-28 15:51
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserDao userDao;

    @Override
    public User getUserById(int id) {
       //jdbc template
        // User user = jdbcTemplate.queryForObject("select * from user where id=?", new Object[]{id},new UserRowMapper());
       //采用JPA的方式连接
        User user =userDao.findById(id);
        return user;
    }

    @Override
    public List<User> getUsers() {
        return jdbcTemplate.query("select * from user",new UserRowMapper());
    }
    class UserRowMapper implements RowMapper<User> {

        @Override
        public User mapRow(ResultSet resultSet, int i) throws SQLException {
            User user=new User();
            user.setId(resultSet.getInt("id"));
            user.setName(resultSet.getString("name"));
            user.setAge(resultSet.getInt("age"));
            user.setAddress(resultSet.getString("address"));
            return user;
        }

    }
}
